const multer = require('@koa/multer')
const COS = require('cos-nodejs-sdk-v5')
const SecretId = "AKIDoTs0uYv1rPggPs4zc07wUlmVx82f15tP"
const SecretKey = "GFyPZS4PTGl0yf4D4exzlGTP5UcT3MN7"
var cos = new COS({
    SecretId: SecretId,
    SecretKey: SecretKey
})
let Bucket = "wechat01-1309303843"
let Region = "ap-guangzhou"
// 商家头像
let confun = function (filename, FilePath) {
    return new Promise((resolve, reject) => {
        cos.uploadFile({
                Bucket,
                Region,
                Key: 'img/' + filename,
                FilePath: FilePath
            })
            .then(res => {
                resolve(res.Location)
            })
            .catch(error => {
                reject(error)
            })
    })
}
// 商品图片内容
let shopfun = function (filename, FilePath) {
    return new Promise((resolve, reject) => {
        cos.uploadFile({
                Bucket,
                Region,
                Key: 'sopping/' + filename,
                FilePath: FilePath
            })
            .then(res => {
                resolve(res.Location)
            })
            .catch(error => {
                reject(error)
            })
    })
}
// 商品图片内容
const storage = multer.diskStorage({
    destination: (req, file, cd) => {
        cd(null, 'upload/img')
    },
    filename: (req, file, cd) => {
        let fileFormat = (file.originalname).split(".")
        let danow = Date.now()
        let ranum = Math.floor(Math.random(0, 1) * 10000)
        let num = `${danow}${ranum}${"."}${fileFormat[fileFormat.length - 1]}`
        // console.log("图片内容", num)
        cd(null, num)
    }
})

const upload = multer({
    storage
})

module.exports = {
    upload,
    confun,
    shopfun
}